<?php
/**
 * @package announcement
 */
class AnnouncementGridFieldActivateAction implements GridField_ColumnProvider, GridField_ActionProvider {
    public function augmentColumns($gridField, &$columns) {
        if(!in_array('Actions', $columns)) {
            $columns[] = 'Actions';
        }
    }

    public function getColumnAttributes($gridField, $record, $columnName) {
        return array('class' => 'col-buttons');
    }

    public function getColumnMetadata($gridField, $columnName) {
        if($columnName == 'Actions') {
            return array('title' => '');
        }
    }

    public function getColumnsHandled($gridField) {
        return array('Actions');
    }

    public function getColumnContent($gridField, $record, $columnName) {
    	Requirements::css('announcement/css/AnnouncementGridFieldActivateAction.css');
        if($record->canEdit()) {
        	$content = '';
        	if(!$record->IsActive){
        		$field = GridField_FormAction::create($gridField, 'Activate' . $record->ID, false, "activate", array('RecordID' => $record->ID))->addExtraClass('gridfield-button-activate')->setAttribute('title', _t('AnnouncementGridFieldActivateAction.BUTTONACTIVATE', 'Activate'))->setAttribute('data-icon', 'accept')->setDescription(_t('AnnouncementGridFieldActivateAction.ACTIVATE_ANNOUNCEMENT', 'Activate Announcement'));
			}
			else{
            	$field = GridField_FormAction::create($gridField, 'Deactivate' . $record->ID, false, "deactivate", array('RecordID' => $record->ID))->addExtraClass('gridfield-button-deactivate')->setAttribute('title', _t('AnnouncementGridFieldActivateAction.BUTTONDEACTIVATE', 'Deactivate'))->setAttribute('data-icon', 'minus-circle')->setDescription(_t('AnnouncementGridFieldActivateAction.DEACTIVATE_ANNOUNCEMENT', 'Deactivate Announcement'));
			}
			
			return $field->Field();
        }
    }

    public function getActions($gridField) {
        return array(
            'activate',
            'deactivate'
        );
    }

    public function handleAction(GridField $gridField, $actionName, $arguments, $data) {
        if($actionName == 'activate' || $actionName = 'deactivate') {
            $item = $gridField->getList()->byID($arguments['RecordID']);
            if(!$item) {
                return;
            }
			
			if(!$item->canEdit()){
				throw new ValidationException(_t('AnnouncementGridFieldActivateAction.ACTION_PERMISSION', 'No permission to perform action for these item'), 0);
			}
			else{
	            if($actionName == 'activate') {
	                $item->IsActive = 1;
	            	$item->write();
	            }
				
	            if($actionName == 'deactivate') {
	                $item->IsActive = 0;
	            	$item->write();
	            }
			}
        }
    }
}
